package org.chench.extra.logsift.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * WebSocket会话处理器
 * @author chench
 * @date 2025.05.17
 */
public class WebSocketSessionHandler {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketSessionHandler.class);
    private static Set<WebSocketSession> sessions = new HashSet<>(0);

    public static WebSocketSession createConcurrentSession(WebSocketSession session) {
        // 创建并发安全的会话装饰器
        return new ConcurrentWebSocketSessionDecorator(
                session,
                10000,  // 发送超时时间（毫秒）
                204800  // 缓冲大小（字节）
        );
    }

    public static void saveSession(WebSocketSession session) {
        sessions.add(session);
    }

    /**
     * 往所有客户端发送消息
     * @param message
     */
    public static void sendMessageSafely(String message) {
        Iterator<WebSocketSession> it = sessions.iterator();
        while(it.hasNext()) {
            WebSocketSession session = it.next();
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(message));
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("send message error: {}, {}", session, message);
                    try {
                        //sessions.remove(session);
                        it.remove();

                        // 关闭会话,同时将session对象移除集合
                        session.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        logger.error("error: {}", ex.getMessage(), ex);
                    }
                }
            }
        }
    }

}
